package com.hengda.museumonline.base;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.VisibleRegion;
import com.amap.api.services.cloud.CloudItem;
import com.amap.api.services.cloud.CloudItemDetail;
import com.amap.api.services.cloud.CloudResult;
import com.amap.api.services.cloud.CloudSearch;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.hengda.museumonline.R;
import com.hengda.museumonline.entity.CityEvent;
import com.hengda.museumonline.rxbus.RxBus;
import com.hengda.museumonline.ui.MainActivity;
import com.hengda.museumonline.utils.CityChengeUtil;
import com.hengda.museumonline.utils.ExhibitionUtil;
import com.hengda.museumonline.utils.ListUtil;
import com.hengda.museumonline.utils.ToastUtil;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Action1;

import static com.yolanda.nohttp.NoHttp.getContext;

/**
 * Created by Administrator on 2016/10/5.
 */

public class MuseumPager {
    private static final String TAG = "ArchPager";
    public MainActivity mainActivity;
    public Bundle savedInstanceState;
    public View view;
    private LinearLayout llCityChenge;
    public ImageView ivMap;
    private AMap aMap;
    public boolean temp = true;
    private TextureMapView textureMapView;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private CloudSearch mCloudSearch;
    private CloudSearch.Query mQuery;
    private List<CloudItem> mCloudItems;
    private ArrayList<CloudItem> items = new ArrayList<CloudItem>();
    private LatLonPoint mPoint1;
    private LatLonPoint mPoint2;
    private LatLonPoint mPoint3;
    private LatLonPoint mPoint4;
    private LatLonPoint mPoint5;
    private String mTableID = "56f0b05b305a2a3288c02f7e";
    private String Keyword = null;
    private int id = -1;
    private LatLngBounds latLngBounds;
    private UiSettings mUiSettings;
    private ArrayList<Marker> markers = new ArrayList<>();
    private CityChengeUtil util;
    private Observable<CityEvent> observable;
    private TextView title;
    public ListUtil listUtil;
    private ImageView location;
    private ImageView goTo;
    private Intent intent;
    private String name;
    private LatLng latLng;
    private ExhibitionUtil exhibitionUtil;

    public MuseumPager(MainActivity mActivity, Bundle savedInstanceState) {
        this.mainActivity = mActivity;
        this.savedInstanceState = savedInstanceState;
        initView();
    }

    public void initView() {
        view = View.inflate(mainActivity, R.layout.museumpager, null);
        title = (TextView) view.findViewById(R.id.title);
        util = new CityChengeUtil();
        llCityChenge = (LinearLayout) view.findViewById(R.id.ll_city_chenge);
        llCityChenge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listUtil.dismissPop();
                ivMap.setImageResource(R.drawable.arch_list);
                temp = true;
                util.getCityFromServer(mainActivity, llCityChenge, "showroom/city");
            }
        });
        ivMap = (ImageView) view.findViewById(R.id.iv_map);
        listUtil = new ListUtil(mainActivity, ivMap);
        listUtil.getPopup(26);
        ivMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (temp) {
                    ivMap.setImageResource(R.drawable.arch_map);
                    listUtil.showPop();
                } else {
                    ivMap.setImageResource(R.drawable.arch_list);
                    listUtil.dismissPop();
                }
                temp = !temp;
            }
        });
        textureMapView = (TextureMapView) view.findViewById(R.id.map);
        textureMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = textureMapView.getMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);
            initMap();
            setUpMap();
            getData();
            searchByBound();
        }
        location = (ImageView) view.findViewById(R.id.location);
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final LatLng latLng = new LatLng(aMap.getMyLocation().getLatitude(), aMap.getMyLocation().getLongitude());
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            }
        });
        goTo = (ImageView) view.findViewById(R.id.goTo);
        goTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (latLng != null) {
                    try {
                        if (isInstallByread("com.autonavi.minimap")) {
                            intent = Intent.getIntent("androidamap://viewMap?sourceApplication=appname&poiname=" +
                                    name + "&lat=" + latLng.latitude + "&lon=" + latLng.longitude + "&dev=0");
                            Log.e("GasStation", "地图客户端已经安装");
                        } else {
                            intent = Intent.getIntent("http://m.amap.com/?q=" + latLng.latitude + "," + latLng.longitude + "&name=" + name);
                            Log.e("GasStation", "没有安装地图客户端");
                        }
                        mainActivity.startActivity(intent);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(mainActivity, "请选择目的地", Toast.LENGTH_SHORT).show();
                }


            }
        });
        observable = RxBus.get().register("city", CityEvent.class);
        observable.subscribe(new Action1<CityEvent>() {
            @Override
            public void call(CityEvent cityEvent) {
                Keyword = cityEvent.getCity();
                id = cityEvent.getId();
                title.setText(Keyword);
                DistrictSearch search = new DistrictSearch(mainActivity);
                DistrictSearchQuery query = new DistrictSearchQuery();
                query.setKeywords(Keyword);
                query.setShowBoundary(true);
                search.setQuery(query);
                search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
                    @Override
                    public void onDistrictSearched(DistrictResult districtResult) {
                        if (districtResult == null || districtResult.getDistrict() == null) {
                            return;
                        }
                        final DistrictItem item = districtResult.getDistrict().get(0);

                        if (item == null) {
                            return;
                        }
                        LatLonPoint centerLatLng = item.getCenter();
                        if (centerLatLng != null) {
                            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(centerLatLng.getLatitude(), centerLatLng.getLongitude()), 10));
                        }
                    }
                });
                search.searchDistrictAsyn();

                listUtil.getPopup(id);
            }
        });
    }

    private void initMap() {
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
            }
        });
    }

    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(new LocationSource() {
            @Override
            public void activate(OnLocationChangedListener onLocationChangedListener) {
                mListener = onLocationChangedListener;
                if (mlocationClient == null) {
                    mlocationClient = new AMapLocationClient(getContext());
                    mLocationOption = new AMapLocationClientOption();
                    mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                    mlocationClient.setLocationOption(mLocationOption);
                    mlocationClient.setLocationListener(new AMapLocationListener() {
                        @Override
                        public void onLocationChanged(AMapLocation amapLocation) {
                            if (mListener != null && amapLocation != null) {
                                if (amapLocation != null && amapLocation.getErrorCode() == 0) {
                                    mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                                    Keyword = amapLocation.getCity();
                                    title.setText(Keyword);
                                    System.out.println("定位城市：" + amapLocation.getCity() + ":" + amapLocation.getAdCode());
                                } else {
                                    String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                                }
                            }
                        }
                    });
                    mlocationClient.startLocation();
                }
            }

            @Override
            public void deactivate() {
                mListener = null;
                if (mlocationClient != null) {
                    mlocationClient.stopLocation();
                    mlocationClient.onDestroy();
                }
                mlocationClient = null;
            }
        });// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
    }

    private void getData() {
        mCloudSearch = new CloudSearch(getContext());
        mCloudSearch.setOnCloudSearchListener(
                new CloudSearch.OnCloudSearchListener() {
                    @Override
                    public void onCloudSearched(CloudResult result, int rCode) {
                        if (rCode == 1000) {
                            if (result != null && result.getQuery() != null) {
                                if (result.getQuery().equals(mQuery)) {
                                    mCloudItems = result.getClouds();
                                    if (mCloudItems != null && mCloudItems.size() > 0) {
                                        //  aMap.clear();
                                        for (CloudItem item : mCloudItems) {
                                            if (aMap.getMapScreenMarkers().isEmpty()) {
                                                // items.add(item);
                                                addMarker(item);
                                            } else {
                                                if (isAddMarker(item)) {
                                                    // items.add(item);
                                                    addMarker(item);
                                                }
                                            }
                                        }
                                        System.out.println("数量：" + aMap.getMapScreenMarkers().size());
                                        for (CloudItem c : items) {

                                        }
                                    } else {

                                    }
                                }
                            } else {
                                ToastUtil.show(getContext(), "没有搜索到相关数据！");
                            }
                        } else

                        {
                            ToastUtil.showerror(getContext(), rCode);
                        }
                    }

                    @Override
                    public void onCloudItemDetailSearched(CloudItemDetail item, int rCode) {
                    }
                }

        );
    }

    private void removeMarker(List<Marker> mapScreenMarkers) {
        for (int i = 0; i < mapScreenMarkers.size(); i++) {
            for (int j = i + 1; i < mapScreenMarkers.size(); i++) {
                double distance = getDistanceBetweenTwoPoints(toScreenLocation1(mapScreenMarkers.get(i)).x,
                        toScreenLocation1(mapScreenMarkers.get(i)).y,
                        toScreenLocation1(mapScreenMarkers.get(j)).x,
                        toScreenLocation1(mapScreenMarkers.get(j)).y);
                if (distance < 160) {
                    mapScreenMarkers.get(i).remove();
                }
            }
        }
    }

    private void addMarker(CloudItem c) {
        Marker marker = aMap.addMarker(new MarkerOptions().title(c.getTitle()).snippet(c.getCustomfield().get("did"))
                .position(new LatLng(c.getLatLonPoint().getLatitude(), c.getLatLonPoint().getLongitude()))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.museum)));
        markers.add(marker);

        Log.d(TAG, "_id" + c.getID());
        Log.d(TAG, "_location" + c.getLatLonPoint().toString());
        Log.d(TAG, "_cloudImage" + c.getCloudImage());
        Log.d(TAG, "_name" + c.getTitle());
        Log.d(TAG, "_address" + c.getSnippet());
        Log.d(TAG, "_caretetime" + c.getCreatetime());
        Log.d(TAG, "_updatetime" + c.getUpdatetime());
        Log.d(TAG, "_distance" + c.getDistance());
        Iterator iter = c.getCustomfield().entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            Log.d(TAG, key + "   " + val);
        }
    }

    private boolean isAddMarker(CloudItem c) {
        for (Marker m : aMap.getMapScreenMarkers()) {
            double distance = getDistanceBetweenTwoPoints(toScreenLocation1(m).x, toScreenLocation1(m).y,
                    toScreenLocation(c).x, toScreenLocation(c).y);
            if (distance < 160) {
                return false;
            }
        }
        return true;
    }

    /**
     * 两点的距离
     *
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @return
     */
    private double getDistanceBetweenTwoPoints(double x1, double y1, double x2,
                                               double y2) {
        double distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)
                * (y1 - y2));
        return distance;
    }

    /**
     * 经纬度转像素
     */
    private Point toScreenLocation(CloudItem item) {
        LatLng mLatlng = new LatLng(item.getLatLonPoint().getLatitude(), item.getLatLonPoint().getLongitude());
        return aMap.getProjection().toScreenLocation(mLatlng);

    }

    /**
     * 经纬度转像素
     */
    private Point toScreenLocation1(Marker item) {
        return aMap.getProjection().toScreenLocation(item.getPosition());

    }


    public void searchByBound() {
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                items.clear();
                if (aMap.getMapScreenMarkers().size() > 1) {
                    removeMarker(aMap.getMapScreenMarkers());
                }

                VisibleRegion visibleRegion = aMap.getProjection().getVisibleRegion(); // 获取可视区域、
                latLngBounds = visibleRegion.latLngBounds;

                for (Marker m : markers) {
                    if (!latLngBounds.contains(m.getPosition())) {
                        m.remove();
                    }
                }
                mPoint1 = new LatLonPoint(latLngBounds.northeast.latitude, latLngBounds.northeast.longitude);
                mPoint2 = new LatLonPoint(latLngBounds.southwest.latitude, latLngBounds.northeast.longitude);
                mPoint3 = new LatLonPoint(latLngBounds.southwest.latitude, latLngBounds.southwest.longitude);
                mPoint4 = new LatLonPoint(latLngBounds.northeast.latitude, latLngBounds.southwest.longitude);
                mPoint5 = new LatLonPoint(latLngBounds.northeast.latitude, latLngBounds.northeast.longitude);
                List<LatLonPoint> points = new ArrayList<LatLonPoint>();
                points.add(mPoint1);
                points.add(mPoint2);
                points.add(mPoint3);
                points.add(mPoint4);
                points.add(mPoint5);
                CloudSearch.SearchBound bound = new CloudSearch.SearchBound(points);
                try {
                    mQuery = new CloudSearch.Query(mTableID, Keyword, bound);
                    mQuery.setPageSize(100);
                    mCloudSearch.searchCloudAsyn(mQuery);
                } catch (AMapException e) {
                    e.printStackTrace();
                }
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                exhibitionUtil = new ExhibitionUtil(mainActivity, marker, view);
                name = marker.getTitle();
                latLng = marker.getPosition();
                System.out.println("我被点击了");
                return true;
            }
        });
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

            }
        });
    }

    public void initData() {

    }
}
